#include "Acceptor.h"
#include <sys/socket.h>
#include <iostream>


Acceptor::Acceptor(const std::string& ip,unsigned short port)
:_addr(ip,port)
,_sock()
{

}
Acceptor::~Acceptor()
{

}
void Acceptor::ready()
{
    setReuseAddr();
    setReusePort();
    bind();
    listen();
}



//设置地址复用
void Acceptor::setReuseAddr()
{
    socklen_t len = 1;
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEADDR,&len,sizeof(len));
}
//设置端口复用
void Acceptor::setReusePort()
{
    socklen_t len = 1;
    /**
     * int setsockopt(int sockfd, int level, int optname,
                      const void optval[.optlen],
                      socklen_t optlen);
     */
    int ret = setsockopt(_sock.fd(),SOL_SOCKET,SO_REUSEPORT,&len,sizeof(len));
    if (-1==ret)
    {
        perror("setsockopt reuseport error");
        return;
    }

}
void Acceptor::bind()
{
    socklen_t len = sizeof(_addr);
    int ret = ::bind(_sock.fd(),(sockaddr*)_addr.getSockAddrPtr(),len);
    if (-1==ret)
    {
        perror("bind error");
        return;
    }
    
}
void Acceptor::listen()
{
    int ret = ::listen(_sock.fd(),128);
    if (-1==ret)
    {
        perror("listen error");
        return;
    }
    
}

int Acceptor::accept()
{
    /**
     * int accept(int sockfd, struct sockaddr *_Nullable restrict addr,
                  socklen_t *_Nullable restrict addrlen);
     */
    int fd = ::accept(_sock.fd(),nullptr,nullptr);
    
    if (-1==fd)
    {
        perror("accept error");
        return fd;
    }
    return fd;
}

int Acceptor::fd()
{
    return _sock.fd();
}